import BaseGroup from '@/components/js/BaseGroup'
import { EventBus } from '@/store/index'
import { COMPONENT_TYPES } from '@/common/const-wb'
import { addEvent, removeEvent } from '@/plugins/dom'

export default class ClickChangeText extends BaseGroup{
  constructor() {
    super();
    //子类覆盖
    this.sortComponents = null;
	}

  start(){
    this.sortComponents = _.sortBy(this.components, (compData) => {
      return compData.commonAttr.itemIndex;
    });

    this.addClickEvent();
    this.initImgSritesheet();
  }

  initImgSritesheet() {
    //事喜大火红
    // .万.乐.事 .利 .吉 .喜 .大 .如 .安 .平 .心 .想 .意  .成 .火  .盈  .红 .财 .门
    //  0  1  2  3   4   5  6   7  8   9  10  11  12  13  14   15  16  17  18
    let randomSteps = [0,1,2,2,3,4,5,5,6,6,7,8,9,10,11,12,13,14,14,15,16,16,17,18];
    randomSteps = _.shuffle(randomSteps);
    _.forEach(this.sortComponents, (compData, index) => {
      let spriteSheetObj = { currentStep: randomSteps[index] };
      this.store.commit("updateComponentAttr", { 
        id: compData.id, 
        interactionData: { spriteSheetObj },
      });
      EventBus.$emit('refreshImgSpriteSheet', { id: compData.id });
    });
  }

  addClickEvent(){
    _.forEach(this.components, (compData) => {
      if(compData.cid == COMPONENT_TYPES.wb_img){
        let img = compData.vueContainer.$refs.img;
        this.onImgClick = this.onImgClick.bind(this);
        addEvent(img, "click", this.onImgClick);
      }
    })
  }

  onImgClick(e){
    e.stopPropagation();
    let img = e.currentTarget;
    let compId = img.parentElement.id;
    let compData = this.componentMap[compId];
    // let imgVueClass = compData.vueContainer;

    let spriteSheetObj = compData.interactionData.spriteSheetObj;
    EventBus.$emit('changeText', { currentStep: spriteSheetObj.currentStep });
  }

  destroy(){
    super.destroy();

    _.forEach(this.components, (compData) => {
      if(compData.cid == COMPONENT_TYPES.wb_process){
        //待处理
      }else if(compData.cid == COMPONENT_TYPES.wb_img){
        let img = compData.vueContainer.$refs.img;
        removeEvent(img, "click", this.onImgClick);
      }
    })
  }
}